package edu.upf.opencities.web.manager.impl;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.axiom.om.util.Base64;

import com.google.gson.Gson;


import edu.upf.opencities.datamodel.Entry;

public class EntryManager {

	
    public String sendEntry(String serviceId, String password, 
    		Entry entryObj) throws IOException {


        	String credentials = serviceId+":"+password;
        	
        	/*Aqui tenemos que pasarle todos los parametros
        	 * para recibir la entry*/
        	Entry entry = entryObj;

            //Now we convert the object into JSON 
    		Gson gson = new Gson();
    		String jsonObj = gson.toJson(entry);
            jsonObj = "{\"entry\":"+jsonObj+"}";
            
    		URL url = new URL("http://opencities.upf.edu/OSN/rest/service/addSecureEntry");

            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestProperty("Authorization", "Basic "+Base64.encode(credentials.getBytes()));
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");

    		

    		//Finally we POST the JSON Object
    		try {
    			
    			DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
    			wr.write(jsonObj.getBytes("UTF-8"));
    		    wr.flush ();
    		    wr.close ();

    			int status = connection.getResponseCode();
    			//System.out.println("Status: "+status);
    			if ((status==200) || (status==201)){

    				return String.valueOf(status);
    			} else {
    				
    				return String.valueOf(status);
    			}
    		} catch (Exception e){
    			return "Problems adding entry. Exception: "+e.getMessage();
    		}

        
        

    }

    

    
	
}